package com.jackrain.nea.shiro.stateful;

import com.jackrain.nea.core.redis.CusRedisTemplate;
import com.jackrain.nea.util.RedisOpsUtil;
import com.jackrain.nea.util.ShiroSessionUtil;
import com.jackrain.nea.util.ValueHolder;
import com.jackrain.nea.web.face.User;
import org.apache.shiro.web.filter.AccessControlFilter;
import org.apache.shiro.web.servlet.ShiroHttpServletRequest;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletResponse;

/**
 * 控制并发人数
 * Created by kunlun on 2016/7/26.
 */
public class KickoutSessionControlFilter extends AccessControlFilter {

    private static Logger logger= LoggerFactory.getLogger(KickoutSessionControlFilter.class.getName());
    
    private String returnUrl = "/c/login";

    @Value("${raincloud.session.max-active}")
    private int maxSession;

    @Override
    protected boolean isAccessAllowed(ServletRequest servletRequest, ServletResponse servletResponse, Object o) throws Exception {
        return false;
    }


    @Override
    protected boolean onAccessDenied(ServletRequest request,ServletResponse response) throws Exception{
        CusRedisTemplate<String,Object> redisTemplate =RedisOpsUtil.getObjRedisTemplate();
        ValueHolder vh = new ValueHolder();
        User user = (User)ShiroSessionUtil.getAttribute("user");
        String sessionId = ((ShiroHttpServletRequest) request).getRequestedSessionId();
        if(user == null){
            Long cnt = redisTemplate.opsForSet().remove("outsession",sessionId);
            if(cnt > 0){
                vh.put("code",-1);
                vh.put("message", "您已从其他地方登陆，请重新登陆");
                response.setCharacterEncoding("utf-8");
                response.setContentType("application/json; charset=utf-8");
                response.getWriter().append(vh.toJSONObject().toJSONString());
                return false;
            }
        }

        if(ShiroSessionUtil.isLogin()){
            return true;
        }
        //((HttpServletResponse)response).sendRedirect("/app/tpl/pub/login/login");
        ((HttpServletResponse)response).setStatus(403);
        ((HttpServletResponse)response).sendRedirect("/app/tpl/pub/login/login");
        return false;
    }
}
